package org.starsource.forum.server.web;

import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URLEncoder;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.starsource.forum.server.dao.MessageDao;
import org.starsource.forum.server.dao.ResourceDao;
import org.starsource.forum.server.domain.Resource;
import org.starsource.forum.server.domain.User;
import org.starsource.forum.server.util.Config;
import org.starsource.forum.server.util.Thumbnail;

public class FileDownloadServlet extends SpringHttpServlet {

	private Config config;
	public void setConfig(Config config) {
		this.config = config;
	}

//	private static org.apache.log4j.Logger logger = org.apache.log4j.LogManager
//	.getLogger(FileDownloadServlet.class.getName());

	private static final long serialVersionUID = -5550230504557535059L;
	
	private ResourceDao resourceDao;
	public void setResourceDao(ResourceDao resourceDao) {
		this.resourceDao = resourceDao;
	}
	
	private MessageDao messageDao;
	public void setMessageDao(MessageDao messageDao) {
		this.messageDao = messageDao;
	}
	
	private void checkThumbnail(User requester, Resource resource) {
		if (null != resource.getThumbUrl() && !"".equals(resource.getThumbUrl())) return;

		try {
			String originPath = requester.getDirectory() + File.separator;
			String thumbnailsPath = config.getThumbnailsPath() + File.separator;
			String thumbnailUrl = java.util.UUID.randomUUID().toString();
			Thumbnail.saveImageAsJpg(originPath + resource.getUrl(), thumbnailsPath + thumbnailUrl, 170, 170);
			BufferedImage image = ImageIO.read(new File(originPath + resource.getUrl()));
			int width = image.getWidth();
			int height = image.getHeight();
			resource.setWidth(width);
			resource.setHeight(height);
			resource.setThumbUrl(thumbnailUrl);
			resourceDao.update(resource);			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		try {
//			logger.debug(request.getRequestURI());
			Resource resource = resourceDao.getResource(new Integer((String)request.getParameter("resourceId")));
			resource.setMessage(messageDao.getMessage(resource.getMessageId()));
			
			String thumbnail = (String)request.getParameter("thumbnail");
			
//			String filename = new String( resource.getUrl().getBytes(), "UTF-8");
		response.setContentType("APPLICATION/OCTET-STREAM");  
		String filename = URLEncoder.encode(resource.getUrl(), "UTF-8"); 
		response.setHeader("Content-Disposition","attachment;   filename=\""   + filename + "\"");  
		String filePath = "";
		java.io.FileInputStream   fileInputStream   = null;
		if ("true".equalsIgnoreCase(thumbnail) || "yes".equalsIgnoreCase(thumbnail)) {
			User requester = ((User)request.getSession().getAttribute("User"));
			this.checkThumbnail(requester, resource);
			filePath = config.getThumbnailsPath() + File.separator;			
			fileInputStream = new   java.io.FileInputStream(filePath + resource.getThumbUrl());
		} else {
			filePath = resource.getMessage().getOwner().getDirectory() + File.separator;			
			fileInputStream = new   java.io.FileInputStream(filePath + resource.getUrl());  
		}

		int   i;  
		while   ((i=fileInputStream.read())   !=   -1)   {  
			response.getOutputStream().write(i);
		}  
		fileInputStream.close();  
		response.flushBuffer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
